package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.common.util.MD5;


import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.vo.LoginSuccessRespVo;
import com.atguigu.gmall.user.vo.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 登陆
     * @param loginVo
     * @return
     */
    @Override
    public LoginSuccessRespVo login(LoginVo loginVo, HttpServletRequest request) {


        //1.先去数据库中查找有无此用户
        String loginName = loginVo.getLoginName();
        String passwd = loginVo.getPasswd();

        //2.根据查询到的账号和密码与数据库中的数据进行对比

        //2.1进项加密,因为数据库中的密码都是加过密的
        String Md5pwd = MD5.encrypt(passwd);
        //2.2 封装查询条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("passwd", Md5pwd);
        queryWrapper.eq("login_name", loginName);
        UserInfo userInfo = this.getOne(queryWrapper);

        //3.根据 userinfo是否为空看是否查到数据
        if (userInfo != null) {
            //数据库中有这个用户
            LoginSuccessRespVo respVo = new LoginSuccessRespVo();
            respVo.setNickName(userInfo.getNickName());
            respVo.setUserId(userInfo.getId());
            String ip = IpUtil.getIpAddress(request);
            userInfo.setIp(ip);
            respVo.setIp(ip);


            //3.1 生成唯一标识的token
            String token = UUID.randomUUID().toString().replace("-", "");
            respVo.setToken(token);

            //将token和用户信息共享到redis
            redisTemplate.opsForValue().set(RedisConst.LOGIN_USER + token,
                    Jsons.toJsonstr(userInfo),RedisConst.LOGIN_USER_TTL, TimeUnit.MILLISECONDS);
            return respVo;

        } else {
            //登陆失败
            return null;
        }


    }

    /**
     * 退出
     * @param token
     */
    @Override
    public void loginOut(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER+token);
    }
}




